package com.yoshino.leetcode.oneHundred.fourteenth;

class Solution {
    public boolean exist(char[][] board, String word) {
        if (board == null || board[0] == null || board.length == 0 || board[0].length == 0 || word == null || "".equals(word)) {
            return false;
        }
        boolean[][] flag = new boolean[board.length][board[0].length];
        char[] chars = word.toCharArray();
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (board[i][j] == chars[0]) {
                    if (bfs(board, i, j, flag, chars, 0)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private boolean bfs(char[][] board, int i, int j, boolean[][] flag, char[] chars, int ind) {
        if (ind == chars.length) {
            return true;
        }
        if (i < 0 || j < 0 || i == board.length || j == board[0].length || flag[i][j] || board[i][j] != chars[ind]) {
            return false;
        }
        flag[i][j] = true;
        boolean res = bfs(board, i + 1, j, flag, chars, ind + 1) ||
                bfs(board, i, j + 1, flag, chars, ind + 1) ||
                bfs(board, i - 1, j, flag, chars, ind + 1) ||
                bfs(board, i, j - 1, flag, chars, ind + 1);
        flag[i][j] = false;
        return res;
    }

    public int movingCount(int m, int n, int k) {
        boolean[][] flag = new boolean[m][n];
        return bfs(0, 0, m, n, k, flag);
    }

    private int bfs(int i, int j, int m, int n, int k, boolean[][] flag) {
        if (i < 0 || j < 0 || i == m || j == n || flag[i][j] || (i / 10 + i % 10 + j / 10 + j % 10) > k) {
            return 0;
        }
        flag[i][j] = true;
        return bfs(i + 1, j, m, n, k, flag) + bfs(i, j+ 1, m, n, k, flag) + 1;
    }
}